package com.birdboot.controller;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;
import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;
import com.birdboot.util.DBUtil;

import java.io.*;
import java.sql.*;

@Controller
public class UserController {
    public static File userDir;
    static {
        userDir = new File("./users");
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("开始处理用户注册！！！");
        // 1、通过表单获取数据
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String ageStr = request.getParameters("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        // 必要验证
        if (username==null||username.isEmpty()||
            password==null||password.isEmpty()||
            nickname==null||nickname.isEmpty()||
            !ageStr.matches("[0-9]+")){
            // 重定向注册失败页面
            response.sentRedirect("/reg_info_error.html");
            return;
        }

        // V20改为数据库操作
        try (
                Connection connection = DBUtil.getConnection();
        ){
            // 判断用户是否重复--用该用户名去userinfo表中查询是否存在
            String sql1 = "SELECT username FROM userinfo WHERE username=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1,username);
            ResultSet rs = ps1.executeQuery();
            if (rs.next()){// 查询到记录说明为重复用户
                response.sentRedirect("/have_user.html");
                return;
            }
            // 不是重复用户就保存到userinfo表中
            String sql2 = "INSERT INTO userinfo(username,password,nickname,age) " +
                          "VALUES(?,?,?,?) ";
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps2.setString(1,username);
            ps2.setString(2,password);
            ps2.setString(3,nickname);
            int age = Integer.parseInt(ageStr);
            ps2.setInt(4,age);
            int num = ps2.executeUpdate();
            if (num>0){
                response.sentRedirect("/reg_success.html");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        File file = new File(userDir,username+".obj");
//        if (file.exists()){
//            response.sentRedirect("/have_user.html");
//            return;
//        }
//        int age = Integer.parseInt(ageStr);
//        User user = new User(username,password,nickname,age);
//        try (
//                FileOutputStream fos = new FileOutputStream(file);
//                ObjectOutputStream oos = new ObjectOutputStream(fos);
//                ){
//            oos.writeObject(user);
//            response.sentRedirect("/reg_success.html");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println("开始处理用户登录！！！");
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        System.out.println(username+","+password);
        if (username == null || username.isEmpty()||
            password == null || password.isEmpty()){
            response.sentRedirect("/login_info_error.html");
            return;
        }
        // V20改为数据库操作
        try (
                Connection connection = DBUtil.getConnection();
        ){
            Statement statement = connection.createStatement();
            String sql = "SELECT username,password FROM userinfo";
            ResultSet resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                String une = resultSet.getString("username");
                String pwd = resultSet.getString("password");
                if (une.equals(username) && pwd.equals(password)){
                    response.sentRedirect("/login_success.html");
                    return;
                }
            }
            response.sentRedirect("/login_fail.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        File file = new File(userDir,username+".obj");
//        if (file.exists()){
//            try(
//                    FileInputStream fis = new FileInputStream(file);
//                    ObjectInputStream ois = new ObjectInputStream(fis);
//                    ){
//                User user = (User) ois.readObject();
//                if (user.getPassword().equals(password)){
//                    response.sentRedirect("/login_success.html");
//                    return;
//                }
//
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
//        }
//        response.sentRedirect("/login_fail.html");
    }
    // v17新增：增加了修改密码的请求，不用修改DispatcherServlet,只用增加index和在UserController里增加updatePWD方法
    @RequestMapping("/updatePWD")
    public void updatePWD(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理修改密码功能！！！");
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        if ( username == null || username.isEmpty()||
             password == null || password.isEmpty()
        ){
            response.sentRedirect("/update_info_error.html");
            return;
        }
        try (
                Connection connection = DBUtil.getConnection();
        ){
            Statement statement = connection.createStatement();
            String sql1 = "SELECT username,password FROM userinfo";
            ResultSet resultSet = statement.executeQuery(sql1);
            while(resultSet.next()) {
                String une = resultSet.getString("username");
                String pwd = resultSet.getString("password");
                String newPwd = request.getParameters("newPassword");
                if (une.equals(username) && pwd.equals(password)){
                    String sql2 = "UPDATE userinfo " +
                            "SET password=? " +
                            "WHERE username=?";
                    PreparedStatement ps = connection.prepareStatement(sql2);
                    ps.setString(1,newPwd);
                    ps.setString(2,une);
                    int num = ps.executeUpdate();
                    if (num>0){
                        response.sentRedirect("/update_success.html");
                        return;
                    }
                }
                response.sentRedirect("/update_info_error.html");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
